package org.hdl.anima;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.hdl.anima.utils.StringUtils;
import org.hdl.anima.utils.XMLFileHelper;


/**
 * 
 * @author qiuhd
 * @since  2014-2-27
 * @version V1.0.0
 */
public final class AppHelper {
	
	private final static String CONF_PATH = "/" ;
	
	private final static String CONF_NAME_STRING = "Server.xml" ;
	
	public static void loadFromStaticXml(Application application)  {
		try {
			Document document= XMLFileHelper.getXMLFile(CONF_PATH + CONF_NAME_STRING);
			Element root = document.getRootElement();
			Element serverElement = root.element("Server");
			
			String serverId = serverElement.attributeValue("id");
			
			if (StringUtils.isEmpty(serverId)) {
				throw new IllegalStateException("Failed to load from " + CONF_NAME_STRING + ",cause : the id attribute is empty!") ;
			}
			
			String host = serverElement.attributeValue("host");
			
			if (StringUtils.isEmpty(host)) {
				throw new IllegalStateException("Failed to load from " + CONF_NAME_STRING + ",cause : the host attribute is empty!") ;
			}
			
			String portStr = serverElement.attributeValue("port");
			
			if (StringUtils.isEmpty(portStr)) {
				throw new IllegalStateException("Failed to load from " + CONF_NAME_STRING + ",cause : the port attribute is empty!") ;
			}
			
			int port = Integer.valueOf(portStr);
			
			String frontendStr = serverElement.attributeValue("frontend");
			
			if (StringUtils.isEmpty(frontendStr)) {
				throw new IllegalStateException("Failed to load from " + CONF_NAME_STRING + ",cause : the frontend attribute is empty!") ;
			}
			
			boolean frontend = Boolean.valueOf(frontendStr);
			
			application.serverConfig = new ServerConifg();

			application.serverConfig.setId(serverId);
			application.serverConfig.setHost(host);
			application.serverConfig.setPort(port);
			application.serverConfig.setFrontend(frontend);
		} catch (Exception e) {
			throw new IllegalStateException("Failed to load from " + CONF_NAME_STRING + ",Cause : Could not found xml file!");
		}
	}
	
	private AppHelper() {}
}

